var motion;
var startTime = 0;
var isMobile = dataStore['fpdoodle'] == '1';
var scopedCheckQueue;
var ua = navigator.userAgent,
    isIe = ua.indexOf('MSIE') > -1 || ua.indexOf('Trident') > -1;
var useLockedControls = true,
    controls = useLockedControls ? ERNO.Locked : ERNO.Freeform;
window.cube = new ERNO.Cube({
    hideInvisibleFaces: isMobile,
    controls: controls,
    renderer: isIe ? ERNO.renderers.IeCSS3D : null
});
cube.hide();
var container = document.getElementById('container');
container.appendChild(cube.domElement);
if (isMobile) {
    document.body.classList.add('mobile');
    document.getElementById('bg').classList.add('graydient');
}
cube.addEventListener('click', function (evt) {
    if (!cube.mouseControlsEnabled) {
        return;
    }
    var cubelet = evt.detail.cubelet,
        face = cubelet[evt.detail.face.toLowerCase()],
        axis = new THREE.Vector3(),
        exclude = new THREE.Vector3(1, 0, 0),
        UP = new THREE.Vector3(0, 1, 0),
        normal = ERNO.Direction.getDirectionByName(face.normal).normal.clone(),
        slice;
    normal.x = Math.abs(normal.x);
    normal.y = Math.abs(normal.y);
    normal.z = Math.abs(normal.z);
    var l = cube.slices.length;
    while (l-- > 0) {
        slice = cube.slices[l];
        axis.copy(slice.axis);
        axis.x = Math.abs(axis.x);
        axis.y = Math.abs(axis.y);
        axis.z = Math.abs(axis.z);
        if (slice.cubelets.indexOf(cubelet) !== -1 &&
            axis.equals(UP)) {
            break;
        }
    }
    var command = slice.name.substring(0, 1);
    if (slice === cube.down) command = command.invert();
    cube.twist(command);
    // cube.slices.
    // cube.hideInvisibleFaces
    // cube.showIds()
});
if (controls === ERNO.Locked) {
    var fixedOrientation = new THREE.Euler(Math.PI * 0.1, Math.PI * -0.25, 0);
    cube.object3D.lookAt(cube.camera.position);
    cube.rotation.x += fixedOrientation.x;
    cube.rotation.y += fixedOrientation.y;
    cube.rotation.z += fixedOrientation.z;
}
cube.camera.position.z = 2000;
cube.camera.fov = 30;
cube.camera.updateProjectionMatrix();
if (isMobile) {
    cube.position.y = 0;
    cube.position.z = 0;
} else {
    cube.position.y = 410;
    cube.position.z = -850;
}
cube.mouseControlsEnabled = false;
cube.keyboardControlsEnabled = false;
cube.twistCountDown = 0;
cube.audioList = [];
cube.audio = 0;
ERNO.RED.hex = '#DC422F';
ERNO.WHITE.hex = '#FFF';
ERNO.BLUE.hex = '#3D81F6';
ERNO.GREEN.hex = '#009D54';
ERNO.ORANGE.hex = '#FF6C00';
ERNO.YELLOW.hex = '#FDCC09';
ERNO.COLORLESS.hex = '#000000';
var Plane = function (cube, name, className) {
    THREE.Object3D.call(this);
    cube.object3D.add(this);
    this.domElement = document.createElement('div');
    this.domElement.classList.add(className);
    this.domElement.id = name;
    this.css3DObject = new THREE.CSS3DObject(this.domElement);
    this.css3DObject.name = 'css3DObject-' + name;
    this.add(this.css3DObject);
};
Plane.prototype = Object.create(THREE.Object3D.prototype);
if (!isIe) {
    var shadow = new Plane(cube, 'shadow', 'shadow');
    shadow.rotation.set(
        (90).degreesToRadians(),
        (0).degreesToRadians(),
        (0).degreesToRadians()
    );
    shadow.position.y = -300;

    function updateShadow() {
        requestAnimationFrame(updateShadow);
        shadow.rotation.z = cube.slicesDictionary['y'].rotation;
    }

    requestAnimationFrame(updateShadow);
}
window.setTimeout(setupLogo, 100);

function setupLogo() {
    cube.rotation.set(
        (25).degreesToRadians(),
        (-45).degreesToRadians(),
        (0).degreesToRadians()
    );
    cube.typeCubeletIds = new Array(8, 17, 16, 23, 20, 12, 21, 25);
    cube.typeCubelets = new ERNO.Group();

    cube.cubelets.forEach(function (cubelet, index) {
        cube.typeCubeletIds.forEach(function (id) {
            if (cubelet.id == id) {
                cube.typeCubelets.add(cubelet);
                // 就是加了 这个8个
                // 8个是什么意思呢，是6面体，每个面9个格子，和8 的关系是？。。
                cubelet.logo = true;
            }
        });
    });
    var stickerLogo = document.getElementsByClassName('stickerLogo');
    if (stickerLogo.length > 0) {
        stickerLogo[0].classList.remove('stickerLogo');
    }
    cube.twistDuration = 0;
    var LOGO_SEQUENCE = 'zzxLFFRDuFLUrl';
    cube.twistCountDown = LOGO_SEQUENCE.length;
    scopedCheckQueue = checkQueue.bind(this, startScrambleAnimation);
    cube.addEventListener('onTwistComplete', scopedCheckQueue);
    cube.twist(LOGO_SEQUENCE);
    // 这句没有 就没有动画了
    // 但是依然是乱的

    function setWhiteBg(selector) {
        var elements = document.querySelectorAll(selector);
        for (var i = 0; i < elements.length; ++i) {
            elements[i].style.backgroundColor = ERNO.WHITE.hex;
        }
    }

    var prefix = '.cubeletId-';
    cube.cubelets.forEach(function (cubelet, index) {
        if (cubelet.logo != true) {
            setWhiteBg(prefix + cubelet.id + ' .sticker');
        }
        if (cubelet.id == 8 || cubelet.id == 17) {
            setWhiteBg(prefix + cubelet.id + ' .sticker.red');
        }
        if (cubelet.id == 21 || cubelet.id == 25) {
            setWhiteBg(prefix + cubelet.id + ' .sticker.yellow');
        }
        if (cubelet.id == 20) {
            setWhiteBg(prefix + cubelet.id + ' .sticker.yellow');
            setWhiteBg(prefix + cubelet.id + ' .sticker.orange');
        }
    });
    // 感觉没有区别

    // console.log(   "cube.cubelets.length")
    // // 是这个
    // console.log(   cube.cubelets.length)
    //
    // cube.typeCubelets.showTexts()
    // cube.typeCubelets.showIds()
    // cube.typeCubelets.showPlastics()
    // 这没什么奇怪的
    // cube.typeCubelets.showExtroverts()
    // 正常
    // cube.typeCubelets.showStickers()
    // 没什么奇怪
    // cube.typeCubelets[0].
    //     cub0=cube.typeCubelets.cubelets[0]
    // console.log("cub0")
    // console.log(cub0)
    // console.log("cub0.id");
    // console.log(cub0.id);
    // 可以获得

    // for (let i = 0; i <3 ; i++) {
    //     console.log(i)
    //     console.log("cube.typeCubelets.cubelets[i]")
    //     console.log(cube.typeCubelets.cubelets[i])
    // }
    setTimeout(scrambleCube, 1000);
}

function enableDeviceMotion() {
    if (!motion) {
        motion = deviceMotion(cube, container);
        motion.decay = 0.1;
        motion.range.x = Math.PI * 0.02;
        motion.range.y = Math.PI * 0.02;
        motion.range.z = 0;
    }
    motion.paused = false;
}

function pauseDeviceMotion() {
    motion.paused = true;
}

function initiateAudio() {
    cube.audioList = [
        'CubeDoodle01',
        'CubeDoodle02',
        'CubeDoodle03',
        'CubeDoodle04',
        'CubeDoodle05',
        'CubeDoodle06',
        'CubeDoodle07',
        'CubeDoodle08'
    ];
    cube.audio = new Html5Audio(cube.audioList,
        'examples/doodle-iframe/media/SingleSounds');
    cube.audio.loadAll();
    cube.addEventListener('onTwistComplete', function (e) {
        cube.audio.play(cube.audioList[
            Math.floor(Math.random() * (cube.audioList.length - 1))]);
    });
}

// 互动的
function startInteractiveCube() {
    if (!isMobile) {
        enableDeviceMotion();
    }
    // var sentCertificate = false;
    startTime = (new Date()).getTime();
    cube.twistDuration = 500;
    cube.moveCounter = 0;
    cube.addEventListener('onTwistComplete', function (e) {
        if (cube.undoing) {
            cube.moveCounter++;
        }
        if (moveCounter) {
            moveCounter.innerText = moveCounter.textContent = cube.moveCounter;
        }
        postParentMessage({'moves': cube.moveCounter});


        // isSliceSameColor = sliceSameId(sliceZ2);
        // isSliceSameColor = sliceSameId(sliceZ1);
        // isSliceSameColor = sliceSameColor(sliceZ1);
        // isSliceSameColor = sliceSameColor(sliceZ1,Direction.front);
        // // 他一直是正确的
        // console.log("isSliceSameColor")
        // console.log(isSliceSameColor)
        // pos(sliceZ1)
        // 0---8 必然是 back
        // look()
        // pos()
        checkTakeChargeAsChiefOf();
        if (crossSplit()) {
            // console.log("crossSplit yess")
            // 是不是要判断 其他的不是/
            crossSplitShow();
        }
        // https://blog.csdn.net/qq_38006520/article/details/81079528
        if (weAreTheWorld()) {
            // console.log("weAreTheWorld yess")
            weAreTheWorldShow();
        }


        if (cube.isSolved()) {
            setTimeout(function () {
                cube.hideInvisibleFaces = false;
                cube.showIntroverts();
                if (shadow && shadow.domElement) {
                    shadow.domElement.style.opacity = '0';
                }
                // if (!sentCertificate) {
                //   sentCertificate = true;
                //   doCertificate();
                //   postParentMessage({'certificate': 1});
                // }
                // 其实这里设置 回到之前速度是不是好点

            }, 1000);
        }
    });
    moveCounter.innerText = moveCounter.textContent = cube.moveCounter;
    if (window.parent != window) {
        uipanel.style.display = '';
        uipanel.style.opacity = '1';
    }
    if (!isMobile) {
        buttonpanel.style.display = 'none';
        moveCounter.style.display = 'none';
    }
    postParentMessage({'controls': 1});
    cube.mouseControlsEnabled = true;
    cube.keyboardControlsEnabled = true;


}

function checkQueue(callback) {
    if (cube.twistQueue.history.length - cube.twistCountDown == 0) {
        cube.removeEventListener('onTwistComplete', scopedCheckQueue);
        callback();
    }
}

window.addEventListener('message', function (e) {
    var data = e.data;
    if (e.origin != dataStore.origin || data.session != dataStore.session) {
        return;
    }
    var update = data['update'];
    if (update) {
        mergeObject(update, dataStore);
        var upgradeText = document.querySelector('#upgradeText div.upgradetext');
        if (upgradeText && update['msgs']) {
            upgradeText.textContent = upgradeText.innerText =
                update['msgs']['Error Version 2'] ||
                dataStore['msgs']['Error Version 2'] || '';
        }
    } else if (data['help']) {
        handleHelpClick();
    } else if (data['moveCounter']) {
        solveCube();
    }
});

function postParentMessage(data) {
    data['session'] = dataStore['session'];
    window.parent && window.parent.postMessage(data, dataStore['origin'] || '*');
}

function startScrambleAnimation() {
    postParentMessage({'transition': 1});
    cube.show();
}

function scrambleCube() {
    new TWEEN.Tween(cube.position)
        .to({
            x: 0,
            y: 0,
            z: 0
        }, 3000)
        .easing(TWEEN.Easing.Quartic.InOut)
        .start(cube.time);
    new TWEEN.Tween(cube.rotation)
        .to({
            x: (25).degreesToRadians(),
            y: (45).degreesToRadians(),
            z: 0
        }, 3000)
        .easing(TWEEN.Easing.Quartic.InOut)
        .start(cube.time);
    cube.twistDuration = 120;
    var WCA_SCRAMBLE_SHORT = 'ddurrdllrBffDUbffdurfdUbll';
    cube.twistCountDown =
        WCA_SCRAMBLE_SHORT.length + cube.twistQueue.history.length;
    cube.twist(WCA_SCRAMBLE_SHORT);
    scopedCheckQueue = checkQueue.bind(this, startInteractiveCube);
    cube.addEventListener('onTwistComplete', scopedCheckQueue);
    cube.cubelets.forEach(function (cubelet, indexCubelets) {
        cubelet.faces.forEach(function (face, indexFaces) {
            var sticker = face.element.getElementsByClassName('sticker')[0];
            if (sticker) {
                var colorNow = sticker.style.backgroundColor;
                if (colorNow) {
                    colorNow = colorNow.replace(/[^\d,]/g, '').split(',');
                    colorNow = {
                        r: colorNow[0].toNumber(),
                        g: colorNow[1].toNumber(),
                        b: colorNow[2].toNumber()
                    };
                    var colorTarget = _.hexToRgb(face.color.hex);
                    new TWEEN.Tween(colorNow)
                        .to({
                            r: colorTarget.r,
                            g: colorTarget.g,
                            b: colorTarget.b
                        }, 500)
                        .onUpdate(function () {
                            sticker.style.backgroundColor = 'rgb(' +
                                colorNow.r.round() + ',' +
                                colorNow.g.round() + ',' +
                                colorNow.b.round() + ')';
                        })
                        .start(cube.time);
                }
            }
        });
    });
}

// 主要是这里的问题，速度设置完，还原之后，还需要把速度设置回去
// 因为这里会设置 转动一下需要的时间，我设置为1ms ，所以很快，所以看起来好像没有转动
function solveCube(_twistDuration) {
    _twistDuration = _twistDuration || 0;

    // cube.twistDuration = _twistDuration;

    let originTwistDuration = cube.twistDuration
    cube.twistDuration = _twistDuration
    let originLen = cube.twistQueue.history.length
    // console.log("originLen")
    // console.log(originLen)
    // 原因是这里设置了 旋转一步的时长，但是还原之后没有设置回去
    while (cube.twistQueue.history.length > 0) cube.undo();
    // 但是直接在这里设置，会造成在旋转中就设置了，应该设个settimeout
    // 但是具体要多少时间不清楚
    // cube.on


    // let twistDurationMs=1
    // solveCube(twistDurationMs);
    // 每次转动一步需要的时间
    // console.log("_twistDuration*originLen")
    // console.log(_twistDuration * originLen)
    // let delay=500
    let delay = 700
    // 这个数字感觉刚好 就算是 1ms 也可以
    setTimeout(() => {
        // console.log("set origin")
        cube.twistDuration = originTwistDuration


        // colorSame= cube.typeCubelets.cubelets[0].back.color===cube.typeCubelets.cubelets[2].back.color
        //  // 可以
        //  console.log("colorSame")
        //  console.log(colorSame)
        // for (let i = 0; i <3 ; i++) {
        //     console.log(i)
        //     console.log("cube.typeCubelets.cubelets[i]")
        //     console.log(cube.typeCubelets.cubelets[i].back.color)
        // }
        // sliceZ1
        // isSliceSameColor = sliceSameColor(sliceZ1,"front");
        // isSliceSameColor = sliceSameColor(sliceZ1,Direction.front);
        // isSliceSameColor = sliceSameColor(sliceZ1,Direction.front);
        // isSliceSameColor = sliceSameId(sliceZ1);
        // isSliceSameColor = sliceSameId(sliceZ2);
        // console.log("isSliceSameColor")
        // console.log(isSliceSameColor)
        // pos()
    }, _twistDuration * originLen + delay)
    // 不加上 1000 的话 还是会在 运行当中速度就慢下来
    // 加个一秒延迟，虽然说 1秒钟之内，你去点击他，还是瞬间转动，但是一秒之后应该可以了

}

// let direction={
//     "z":"front"
// }
class Direction {
// this.front="front"


    constructor() {
        // 这里 点不出来的
        this.front = "front"
        this.back = "back"
        this.left = "left"
        this.right = "right"
        this.up = "up"
        this.down = "down"

    }

}

function getFaceColorLstOfIdxes(slice, idxes, direction) {
    let cubelets = cube.cubelets
    let colorLst = []
    for (let idx of idxes) {
        let color = cubelets[slice[idx]][direction].color
        colorLst.push(color)
    }
    // for (let x of slice) {
    //     // let color=cubelets[i]["back"].color
    //     // 0--8
    //     let color=cubelets[x][direction].color
    //     colorLst.push(color)
    // }
    return colorLst;
}

function getFaceColorLstOfIdxesRetTwoColorLst(slice, idxes, direction) {
    let cubelets = cube.cubelets
    let colorLst = []
    let colorLstNotContain = []
    // for (let idx of idxes) {
    //     let color = cubelets[slice[idx]][direction].color
    //     colorLst.push(color)
    // }
    // let  allIdxes=[]

    // https://www.cnblogs.com/sangwl/p/10185116.html
    for (let idx of allIdxes) {
        // let color = cubelets[slice[idx]][direction].color
        // colorLst.push(color)
        let trueIdx = slice[idx];
        // let color = cubelets[slice[idx]][direction].color
        let color = cubelets[trueIdx][direction].color;
        // let color=cubelets[x][direction].color
        if (idx in idxes) {
// 需要的 idx
            colorLst.push(color)
            // 这里的 color 要一样
        } else {
            colorLstNotContain.push(color)
        }
    }
// if(!listSame(colorLst))


    // for (let i =0;i<slice.length;i++) {
    // // for (let x of slice) {
    //     // let color=cubelets[i]["back"].color
    //     // 0--8
    //
    //     // for (let idx of idxes) {
    //     //     // let color = cubelets[slice[idx]][direction].color
    //     //     // colorLst.push(color)
    //     //     if(idx in allIdxes){
    //     //
    //     //     }
    //     // }
    //
    //
    //     let color=cubelets[x][direction].color
    //     colorLst.push(color)
    // }
    return {
        "colorLst": colorLst,
        "colorLstNotContain": colorLstNotContain
    }
    // return colorLst;
}


function lstHave(lst,obj) {
    for(let o of lst ){
        if(o===obj){
            return true;
        }
    }
    return false;
}
function sameColorSlice(slice, idxes, direction) {
    let cubelets = cube.cubelets
    let colorLst = []
    let colorLstNotContain = []
    // for (let idx of idxes) {
    //     let color = cubelets[slice[idx]][direction].color
    //     colorLst.push(color)
    // }
    // let  allIdxes=[]

    // https://www.cnblogs.com/sangwl/p/10185116.html
    for (let idx of allIdxes) {
        // let color = cubelets[slice[idx]][direction].color
        // colorLst.push(color)
        let trueIdx = slice[idx];
        // let color = cubelets[slice[idx]][direction].color
        let color = cubelets[trueIdx][direction].color;
        // let color=cubelets[x][direction].color
        // if (idx in idxes) {
        if (lstHave(idxes,idx)) {
// 需要的 idx
            colorLst.push(color)
            // 这里的 color 要一样
        } else {
            colorLstNotContain.push(color)
        }
    }
    // console.log("colorLst")
    // console.log(colorLst)
    // console.log("colorLstNotContain")
    // console.log(colorLstNotContain)
    if (!listSame(colorLst)) {
        return false;
    }
    for (let colr of colorLst) {
        // console.log("colr")
        // console.log(colr)
        // if (colr in colorLstNotContain) {
        //     return false;
        // }

        if (lstHave(colorLstNotContain,colr)) {
            return false;
        }
    }

    return true;

    // for (let i =0;i<slice.length;i++) {
    // // for (let x of slice) {
    //     // let color=cubelets[i]["back"].color
    //     // 0--8
    //
    //     // for (let idx of idxes) {
    //     //     // let color = cubelets[slice[idx]][direction].color
    //     //     // colorLst.push(color)
    //     //     if(idx in allIdxes){
    //     //
    //     //     }
    //     // }
    //
    //
    //     let color=cubelets[x][direction].color
    //     colorLst.push(color)
    // }

    // return   {
    //     "colorLst":colorLst,
    //     "colorLstNotContain":colorLstNotContain
    // }

    // return colorLst;
}


function getFaceColorLst(slice, direction) {
    let cubelets = cube.cubelets
    let colorLst = []
    for (let x of slice) {
        // let color=cubelets[i]["back"].color
        // 0--8
        let color = cubelets[x][direction].color
        colorLst.push(color)
    }
    return colorLst;
}

function look() {
    // cubeletsDivs= document.getElementsByClassName("cubelet")
    // cubeletsDivs= document.getElementsByClassName("face axisZ  faceExtroverted")
    // faces= document.getElementsByClassName("face axisZ  faceExtroverted")
    faces = document.getElementsByClassName("face axisZ faceFront  faceExtroverted")
    // id 必然是 0---8
    // cubeletsDivs
    // faces.for()
    ids = []
    for (let face of faces) {
        idSpan = face.getElementsByClassName("id")[0].getElementsByTagName("span")[0];
        idTxt = idSpan.textContent
        ids.push(idTxt)
    }
    console.log("ids")
    console.log(ids)

}

function getFaceOfDiv() {

}


function showShieldJoin() {
    // shiled
    // $frame.style.display="none";
    container.style.display = "none";
    // canvas.
    // document.getElementById("shiled").style.display="block";
    // $shield.style.display="block";
    divShield.style.display = "block";
    // shield.shuffle()
    // 这里都可以获得 shield
    // 就会比较混乱
    setTimeout(() => {

        shield.join()
    }, 500)

}


function checkTakeChargeAsChiefOf() {
    let isTakeChargeAsChiefOf = takeChargeAsChiefOf();
    // console.log("isTakeChargeAsChiefOf")
    // console.log(isTakeChargeAsChiefOf)
    if (isTakeChargeAsChiefOf === true) {
        showShieldJoin();
        // console.log("showShieldJoin")
    }
}

function weAreTheWorldShow() {
    $bg.css("background", "url(img/greatLakes.jfif) no-repeat")
}

// https://www.cnblogs.com/lmyau/p/7736269.html
function crossSplitShow() {
    // console.log("crossSplitShow")
    // $bg.style.background="img/短发女孩 十字架 4k动漫.jpg"
    // 必然是要全部设置 不然就用不了
    // $bg.style.background="#f3f3f3 url('img/短发女孩 十字架 4k动漫.jpg')  no-repeat right top"
    // $bg.style.background-image="url(img/短发女孩 十字架 4k动漫.jpg)"
    // $bg.css("background : #f3f3f3 url('img/短发女孩 十字架 4k动漫.jpg')  no-repeat right top")
    // $bg.css("background",  "url('img/短发女孩 十字架 4k动漫.jpg')" )
    // $bg.css("background",  "url(img/shizi1024.jpg)" )
    // $bg.css("background",  "url(img/shizi1550.jpg) no-repeat" )
    // $bg.css("background",  "url(img/shizi1550x900.jpg) no-repeat" )
    // $bg.css("background",  "url(img/shizi1600x800.jpg) no-repeat" )
    // $bg.css("background",  "url(img/shizi1536x864.jpg) no-repeat" )
    $bg.css("background", "url(img/shizi1536x864.jpg) no-repeat")
    // css background size
    // background-size:80px 60px;
}


// 四海一心
function weAreTheWorld() {
    // let faceFrontColors = getFaceColorLstOfIdxes(faceFront, weAreTheWorldIdxes, "front");    // 对的
    // let faceBackColors = getFaceColorLstOfIdxes(faceBack, weAreTheWorldIdxes, "back");    // 对的
    // // let faceBackColors = getFaceColorLst(faceBack,"back");    // 对的
    // let faceLeftColors = getFaceColorLstOfIdxes(faceLeft, weAreTheWorldIdxes, "left");    // 对的
    // let faceRightColors = getFaceColorLstOfIdxes(faceRight, weAreTheWorldIdxes, "right");    // 对的
    // let faceUpColors = getFaceColorLstOfIdxes(faceUp, weAreTheWorldIdxes, "up");    // 对的
    // let faceDownColors = getFaceColorLstOfIdxes(faceDown, weAreTheWorldIdxes, "down");    // 对的
    //
    //
    // let faceFrontColors = getFaceColorLstOfIdxesRetTwoColorLst(faceFront, weAreTheWorldIdxes, "front");    // 对的
    // let faceBackColors = getFaceColorLstOfIdxes(faceBack, weAreTheWorldIdxes, "back");    // 对的
    // // let faceBackColors = getFaceColorLst(faceBack,"back");    // 对的
    // let faceLeftColors = getFaceColorLstOfIdxes(faceLeft, weAreTheWorldIdxes, "left");    // 对的
    // let faceRightColors = getFaceColorLstOfIdxes(faceRight, weAreTheWorldIdxes, "right");    // 对的
    // let faceUpColors = getFaceColorLstOfIdxes(faceUp, weAreTheWorldIdxes, "up");    // 对的
    // let faceDownColors = getFaceColorLstOfIdxes(faceDown, weAreTheWorldIdxes, "down");    // 对的

    return sameColorSlice(faceFront, weAreTheWorldIdxes, "front") ||
        sameColorSlice(faceBack, weAreTheWorldIdxes, "back") ||
        sameColorSlice(faceLeft, weAreTheWorldIdxes, "left") ||
        sameColorSlice(faceRight, weAreTheWorldIdxes, "right") ||
        sameColorSlice(faceUp, weAreTheWorldIdxes, "up") ||
        sameColorSlice(faceDown, weAreTheWorldIdxes, "down");
    // console.log("faceFrontColors")
    // console.log(faceFrontColors)
    //
    // console.log("faceBackColors")
    // console.log(faceBackColors)
    // console.log("faceLeftColors")
    // console.log(faceLeftColors)

    // let haveSliceSame =
    //
    //     // 就是 根据法向量和 这一片的那些方块，去看颜色是不是都一样的
    //     listSame(faceFrontColors) ||
    //     listSame(faceBackColors) ||
    //     listSame(faceLeftColors) ||
    //     listSame(faceRightColors) ||
    //     listSame(faceUpColors) ||
    //     listSame(faceDownColors);
    //
    // return haveSliceSame;

}


// 十字劈
function crossSplit() {
    // let faceFrontColors = getFaceColorLstOfIdxes(faceFront, crossIdxes, "front");    // 对的
    // let faceBackColors = getFaceColorLstOfIdxes(faceBack, crossIdxes, "back");    // 对的
    // // let faceBackColors = getFaceColorLst(faceBack,"back");    // 对的
    // let faceLeftColors = getFaceColorLstOfIdxes(faceLeft, crossIdxes, "left");    // 对的
    // let faceRightColors = getFaceColorLstOfIdxes(faceRight, crossIdxes, "right");    // 对的
    // let faceUpColors = getFaceColorLstOfIdxes(faceUp, crossIdxes, "up");    // 对的
    // let faceDownColors = getFaceColorLstOfIdxes(faceDown, crossIdxes, "down");    // 对的
    //
    // // console.log("faceFrontColors")
    // // console.log(faceFrontColors)
    // //
    // // console.log("faceBackColors")
    // // console.log(faceBackColors)
    // // console.log("faceLeftColors")
    // // console.log(faceLeftColors)
    // let haveSliceSame =
    //
    //     // 就是 根据法向量和 这一片的那些方块，去看颜色是不是都一样的
    //     listSame(faceFrontColors) ||
    //     listSame(faceBackColors) ||
    //     listSame(faceLeftColors) ||
    //     listSame(faceRightColors) ||
    //     listSame(faceUpColors) ||
    //     listSame(faceDownColors);
    //
    // return haveSliceSame;

    return sameColorSlice(faceFront, crossIdxes, "front") ||
        sameColorSlice(faceBack, crossIdxes, "back") ||
        sameColorSlice(faceLeft, crossIdxes, "left") ||
        sameColorSlice(faceRight, crossIdxes, "right") ||
        sameColorSlice(faceUp, crossIdxes, "up") ||
        sameColorSlice(faceDown, crossIdxes, "down");

}

// 独当一面
function takeChargeAsChiefOf() {
    let faceFrontColors = getFaceColorLst(faceFront, "front");    // 对的
    let faceBackColors = getFaceColorLst(faceBack, "back");    // 对的
    // let faceBackColors = getFaceColorLst(faceBack,"back");    // 对的
    let faceLeftColors = getFaceColorLst(faceLeft, "left");    // 对的
    let faceRightColors = getFaceColorLst(faceRight, "right");    // 对的
    let faceUpColors = getFaceColorLst(faceUp, "up");    // 对的
    let faceDownColors = getFaceColorLst(faceDown, "down");    // 对的
    // 不行的啊
    // listSame(faceFrontColors);


    let haveSliceSame =

        // 就是 根据法向量和 这一片的那些方块，去看颜色是不是都一样的
        listSame(faceFrontColors) ||
        listSame(faceBackColors) ||
        listSame(faceLeftColors) ||
        listSame(faceRightColors) ||
        listSame(faceUpColors) ||
        listSame(faceDownColors);

    return haveSliceSame;

}

function listSame(lst) {
    if (lst == null) return false;
    // if(lst.length()<=0)return  false;
    if (lst.length <= 0) return false;
    let elm0 = lst[0];
    // for (let i = 1; i < lst.length(); i++) {
    for (let i = 1; i < lst.length; i++) {
        if (elm0 !== lst[i]) return false;
    }
    return true;
}

function colorSame() {

}

function pos(slice) {
    let cubelets = cube.cubelets
    // 这个一直是true的
    // let cube0Color = cube.typeCubelets.cubelets[0].back.color
    // cube0=   cubelets[0]
    // console.log(cube0.addressX+" "+cube0.addressY+" "+cube0.addressX)
    // let cube0Color =cubelets[0].addressX
    // let cube0Color =cubelets[0].addressY
    // let cube0Color =cubelets[0].addressZ
    // console.log("cube0Color")
    // console.log(cube.cubelets[0])
    // 列表里的 顺序会变
    // id 也是跟着 那个块的吗
    // let sliceZ3Colors = getFaceColorLst(sliceZ3,"back");
    // console.log("sliceZ3Colors")
    // console.log(sliceZ3Colors)
    // console.log("Direction.front")
    // console.log(Direction.front)
    // let sliceZ1Colors = getFaceColorLst(sliceZ1,"front");
    // let sliceZ3Colors = getFaceColorLst(sliceZ3,"front");
    // // let sliceX1LeftColors = getFaceColorLst(sliceX1,"left");  //错误
    // let sliceX1RightColors = getFaceColorLst(sliceX1,"right");    // 对的
    // let sliceX3RightColors = getFaceColorLst(sliceX3,"right");    // 对的
    // let faceLeftColors = getFaceColorLst(sliceX3,"left");    // 对的
    let faceFrontColors = getFaceColorLst(faceFront, "front");    // 对的
    let faceBackColors = getFaceColorLst(faceBack, "back");    // 对的
    let faceLeftColors = getFaceColorLst(faceLeft, "left");    // 对的
    let faceRightColors = getFaceColorLst(faceRight, "right");    // 对的
    let faceUpColors = getFaceColorLst(faceUp, "up");    // 对的
    let faceDownColors = getFaceColorLst(faceDown, "down");    // 对的
    // 不行的啊
    listSame(faceFrontColors);
    console.log("faceUpColors")
    console.log(faceUpColors)
    console.log("faceFrontColors")
    console.log(faceFrontColors)

    // console.log("sliceZ1Colors")
    // console.log(sliceZ1Colors)
    //
    // console.log("sliceZ3Colors")
    // console.log(sliceZ3Colors)

    // console.log("sliceX1LeftColors")
    // console.log(sliceX1LeftColors)

    // console.log("sliceX1RightColors")
    // console.log(sliceX1RightColors)

    // console.log("sliceX3RightColors")
    // console.log(sliceX3RightColors)


    // let ids=[]
    // let idLefts=[]
    // let idRights=[]
    // let idUps=[]
    // let idDowns=[]
    // let idBacks=[]
    //  // for (let i = 0; i < 9; i++) {
    //  // 0--9
    //  // for (let x of sliceZ3) {
    //  //    let color=cubelets[i]["back"].color
    //  // }
    //  for (let i = 0; i < 27; i++) {
    //      // console.log(cubelets[i].id)
    //      // console.log(cube.cubelets[i].id)
    //      // id=cubelets[i].id
    //      // id=cubelets[i].back.color
    //      // id=cubelets[i].front.color
    //      // id=cubelets[i]
    //      id=cubelets[i]["front"].color
    //      idLeft=cubelets[i]["left"].color
    //      idRight=cubelets[i]["right"].color
    //      idUp=cubelets[i]["up"].color
    //      idDown=cubelets[i]["down"].color
    //      idBack=cubelets[i]["back"].color
    //      idLefts.push(idLeft)
    //      idRights.push(idRight)
    //      idUps.push(idUp)
    //      idDowns.push(idDown)
    //      idBacks.push(idBack)
    //      // 这不是可以的吗
    //      // console.log(cubelets[i].id)
    //      // console.log(cubelets[i].id)
    //      ids.push(id)
    //  }
    //  // console.log(ids)
    //  console.log("idLefts")
    //  console.log(idLefts)
    //  console.log("idRights")
    //  console.log(idRights)
    //
    //  console.log("idUps")
    //  console.log(idUps)
    //  console.log("idDowns")
    //  console.log(idDowns)
    //
    //  console.log("idBacks")
    //  console.log(idBacks)

    // for(i of slice){
    //     let cube=cubelets[i]
    //     console.log(cube.addressX+" "+cube.addressY+" "+cube.addressX)
    //
    // }
    // for(cube of cubelets){
    //     console.log(cube.addressX+" "+cube.addressY+" "+cube.addressX)
    // }
}

function getCubeletFaceByDirection(cubelet, direction) {
    if (direction === ERNO.Direction.FRONT) {
        // let cube0Color =cube0[direction].color
        // let cube0Color =cube0.front.color
        // cube0.getDirectionById()
        // cube0.getIdByName()
        // cube0.getCubelet()
        return cubelet.front;
    } else if (direction === ERNO.Direction.BACK) {
        return cubelet.back;
    } else if (direction === ERNO.Direction.UP) {
        return cubelet.up;
    } else if (direction === ERNO.Direction.DOWN) {
        return cubelet.down;
    } else if (direction === ERNO.Direction.LEFT) {
        return cubelet.left;
    } else if (direction === ERNO.Direction.RIGHT) {
        return cubelet.right;
    }

}

// 每个面需要不同的 轴
// axis
function sliceSameColor(slice, direction) {
    let cubelets = cube.cubelets
    // 这个一直是true的
    // let cube0Color = cube.typeCubelets.cubelets[0].back.color
    // let cube0Color =cubelets[0].back.color
    // let cube0Color =cubelets[0][direction].color
    let cube0 = cubelets[0]
    // if(direction===ERNO.Direction.FRONT){
    //     let cube0Color =cube0[direction].color
    //     let cube0Color =cube0.front.color
    //     cube0.getDirectionById()
    //     cube0.getIdByName()
    //     cube0.getCubelet()
    // }

    let cube0Color = getCubeletFaceByDirection(cube0, direction)

    // js 取得 元素 根据字符串
    // cube0.
    // console.log("cube0Color")
    // console.log(cube0Color)
    // ===cube.typeCubelets.cubelets[2].back.color
    // var zLine =ZLine;
    // let cube0Color=getFaceColorByVector(side1[0], zLine);
    // cubelets[0].up
    // cubelets[0].down
    // var zLine =ZLine;
    // 可以根据 块和 法向量 知道这块的 这个面的颜色
    // let cube0Color=getFaceColorByVector(side[0], axis);

    // for (let cube of side1) {
    //     getFaceColorByVector(cube, zLine)

    // }
    // for (let i = 0; i < side1.length; i++) {
    //     const colorOfCube = side1[i];
    //     if(colorOfCube!=cube0Color){

    //     }

    // }

    // for (let cube of side1) {
    //     getFaceColorByVector(cube, zLine)

    // }

    for (let i = 1; i < slice.length; i++) {
        // const colorOfCube = side[i];
        // console.log("side")
        // console.log(side)
        // 可不敢乱打印 好卡
        // const colorOfCube   =getFaceColorByVector(side[i], axis);
        // const colorOfCube = cube.typeCubelets.cubelets[i].back.color
        // const colorOfCube = cubelets[i].back.color
        // const colorOfCube = cubelets[i][direction].color
        let colorOfCube = getCubeletFaceByDirection(cubelets[i], direction)
        // console.log("colorOfCube")
        // console.log(colorOfCube)
        if (colorOfCube !== cube0Color) {
            return false;

        }

    }
    return true;
}


// axis
function sliceSameId(slice) {
    // cube.cubelets
    // let cube0Color = cube.typeCubelets.cubelets[0].back.id
    let cubelets = cube.cubelets
    let cube0Color = cubelets[0].back.id
    // console.log("cube0Color")
    // console.log(cube0Color)
    // console.log("length")
    // console.log(cube.typeCubelets.cubelets.length)
    // cube8= cube.typeCubelets.cubelets[8]
    // console.log("cube8")
    // console.log(cube8)
    for (let i = 1; i < slice.length; i++) {

        // const colorOfCube = cube.typeCubelets.cubelets[i].back.id
        const colorOfCube = cubelets[i].back.id
        // console.log("colorOfCube")
        // console.log(colorOfCube)
        if (colorOfCube !== cube0Color) {
            return false;

        }

    }
    return true;
}


// let sliceZ1 = [0, 1, 2, 3, 4, 5, 6, 7, 8];
// let face

// let sliceX1 = [11, 14, 17, 20, 23, 26, 2, 5, 8];
// let sliceX2 = [10, 13, 16, 19, 22, 25, 1, 4, 7];
// let sliceX3 = [9, 12, 15, 18, 21, 24, 0, 3, 6];
// let sliceX3 = [9, 12, 15, 18, 21, 24, 0, 3, 6];
// let sliceX3 = [8, 11, 14, 17, 20, 23, -1, 2, 5];

let sliceX1 = [20, 23, 26, 11, 14, 17, 2, 5, 8];
let sliceX2 = [19, 22, 25, 10, 13, 16, 1, 4, 7];
let sliceX3 = [18, 21, 24, 9, 12, 15, 0, 3, 6];

// let sliceZ3 = [19, 18, 21, 22, 24, 25, 20, 23, 26];
let sliceZ3 = [18, 19, 20, 21, 22, 23, 24, 25, 26];
// let sliceZ3 = [19, 18, 21, 22, 24, 25, 20, 23, 26];
// let sliceZ2 = [10, 9, 12, 13, 15, 16, 11, 14, 17];
let sliceZ2 = [9, 10, 11, 12, 13, 14, 15, 16, 17];
// let sliceZ1 = [1, 0, 3, 4, 6, 7, 2, 5, 8];
let sliceZ1 = [0, 1, 2, 3, 4, 5, 6, 7, 8];


let sliceY1 = [0, 1, 2, 9, 10, 11, 18, 19, 20];
let sliceY2 = [3, 4, 5, 12, 13, 14, 21, 22, 23];
let sliceY3 = [6, 7, 8, 15, 16, 17, 24, 25, 26];

let crossIdxes = [1, 3, 4, 5, 7];
let weAreTheWorldIdxes = [0, 2, 4, 6, 8];
let allIdxes = [0, 1, 2, 3, 4, 5, 6, 7, 8];

let faceBack = [18, 19, 20, 21, 22, 23, 24, 25, 26];
let faceFront = [0, 1, 2, 3, 4, 5, 6, 7, 8,];
let faceDown = [6, 7, 8, 15, 16, 17, 24, 25, 26];
let faceUp = [0, 1, 2, 9, 10, 11, 18, 19, 20];
let faceRight = [2, 5, 8, 11, 14, 17, 20, 23, 26];
let faceLeft = [0, 3, 6, 9, 12, 15, 18, 21, 24];
// let sliceY2 = [3, 4, 5, 12, 13, 14, 21, 22, 23];
// let sliceY3 =  [6, 7, 8, 15, 16, 17, 24, 25, 26];

var helpBubble = document.getElementById('helpbubble');
var helpButton = document.getElementById('helpbutton');
var helpIndex = 0;
var helpNext = document.getElementById('helpnext');
var helpText = document.getElementById('helptext');
var helpImage = document.getElementById('helpimage');
var moveCounter = document.getElementById('movecounter');
var searchButton = document.getElementById('searchbutton');
var shareBubble = document.getElementById('sharebubble');
var shareButton = document.getElementById('sharebutton');
var shareEmail = document.getElementById('shareemail');
var shareFacebook = document.getElementById('sharefacebook');
var shareGPlus = document.getElementById('sharegplus');
var shareShortLink = document.getElementById('shareshortlink');
var shareTwitter = document.getElementById('sharetwitter');
var uipanel = document.getElementById('uipanel');
var buttonpanel = document.getElementById('buttonpanel');
if (window.navigator.userAgent.match(/iP(hone|od|ad)/i)) {
    shareEmail.style.display = 'none';
}

function setMobileIcon(element) {
    element.className = element.className.replace('_64', '_96');
}

if (isMobile) {
    setMobileIcon(shareGPlus);
    setMobileIcon(shareFacebook);
    setMobileIcon(shareTwitter);
    setMobileIcon(shareEmail);
    setMobileIcon(searchButton);
    setMobileIcon(helpButton);
    setMobileIcon(shareButton);
    shareShortLink.style.display = 'none';
}

function addListener(element, listener) {
    if (isMobile) {
        element.addEventListener('touchstart', listener);
    } else {
        element.addEventListener('click', listener);
    }
}

// function getShortlinkForSharing() {
//   var shortlink = dataStore['shortlink'] || '//google.com/doodles';
//   return shortlink.replace(/.*\/\//, 'http://');
// }
// addListener(shareGPlus, function(e) {
//   window.open('https://plus.google.com/share?url=' +
//       encodeURIComponent(getShortlinkForSharing()));
// });
// addListener(shareFacebook, function(e) {
//   window.open('http://www.facebook.com/sharer.php?u=' +
//       encodeURIComponent(getShortlinkForSharing()));
// });
// addListener(shareTwitter, function(e) {
//   window.open('http://twitter.com/intent/tweet?status=' +
//       encodeURIComponent(dataStore['msgs']['Share Message'] + ' ' +
//       getShortlinkForSharing()));
// });
// addListener(shareEmail, function(e) {
//   window.open('mailto:?subject=' +
//       encodeURIComponent(dataStore['msgs']['Share Message']) +
//       '&body=' + encodeURIComponent(getShortlinkForSharing()));
// });
// addListener(searchButton, function(e) {
//   postParentMessage({'search': 1});
// });
// function updateHelp() {
//   helpText.textContent = helpText.innerText =
//       dataStore['msgs']['Directions ' + helpIndex];
//   helpNext.textContent = helpNext.innerText =
//       dataStore['msgs']['Directions UI ' + (helpIndex < 2 ? 1 : 2)];
//   if (helpIndex == 1) {
//     helpImage.classList.remove('two');
//     helpImage.classList.add('one')
//   } else if (helpIndex == 2) {
//     helpImage.classList.remove('one');
//     helpImage.classList.add('two')
//   }
// }
// function handleHelpClick(e) {
//   if (helpBubble.style.display == 'none') {
//     helpBubble.style.display = 'block';
//     helpBubble.style.pointerEvents = 'auto';
//     helpIndex = 1;
//     updateHelp();
//   } else {
//     helpBubble.style.display = 'none';
//     helpBubble.style.pointerEvents = 'none';
//   }
//   shareBubble.style.opacity = '0';
// }
// helpBubble.dir = dataStore['dir'];
// addListener(helpBubble, function(e) {
//   helpIndex++;
//   if (helpIndex > 2) {
//     helpBubble.style.display = 'none'
//     helpBubble.style.pointerEvents = 'none';
//   } else {
//     helpBubble.style.display = 'block'
//     updateHelp();
//   }
//   shareBubble.style.opacity = 'none';
//   e.preventDefault && e.preventDefault();
//   return false;
// });
// addListener(helpButton, handleHelpClick);
// addListener(container, function(e) {
//   helpBubble.style.display = 'none';
//   helpBubble.style.pointerEvents = 'none';
//   shareBubble.style.opacity = '0';
// });
// addListener(shareButton, function(e) {
//   shareBubble.style.opacity = shareBubble.style.opacity == '0' ? '1' : '0';
//   helpBubble.style.display = 'none';
//   shareShortLink.value = dataStore['shortlink'].replace(/^\/\//, '');
// });
// shareShortLink.addEventListener('mouseup', function(e) {
//   e.preventDefault();
//   shareShortLink.select();
// });

addListener(document.getElementById("solve"), function (e) {
    // solveCube(1000);
    // solveCube(1);
    // solveCube(100);
    // let originTwistDuration = cube.twistDuration
    // let twistDurationMs=1
    // let twistDurationMs = 50
    let twistDurationMs = 1
    // let twistDurationMs = 500
    solveCube(twistDurationMs);
    // 每次转动一步需要的时间
    // setTimeout(()=>{
    //   cube.twistDuration=originTwistDuration
    // },twistDurationMs*cube.twistQueue.isLooping)

    // ERNO.show();
    // ERNO. Group.showTexts()
    // cube.group.
    // cube.typeCubeletIds
});


// console.log("0 in allIdxes")
// console.log(0 in allIdxes)
console.log(10 in allIdxes)
// 可以